//
//  main.m
//  Demo0024
//
//  Created by zTercel on 13-3-6.
//  Copyright (c) 2013年 zTercel. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        NSString* fileName  = NSTemporaryDirectory();
        NSString* txtPath  = [[fileName stringByAppendingPathComponent:@"testfile"]stringByAppendingPathExtension:@"txt"];
        NSString* newPath   = [[fileName stringByAppendingPathComponent:@"newfile"]stringByAppendingPathExtension:@"txt"];
        NSURL* url = [NSURL URLWithString:@"http://www.baidu.com"];
        
        // create source file
        NSData* data = [NSData dataWithContentsOfURL:url];
        NSFileManager* fm = [NSFileManager defaultManager];
        [fm createFileAtPath:txtPath contents:data attributes:nil];
        [fm createFileAtPath:newPath contents:nil attributes:nil];
        NSLog(@"data save to %@", txtPath);
        
        
        NSFileHandle* fileReading = [NSFileHandle fileHandleForReadingAtPath: txtPath];
        NSFileHandle* fileWriting = [NSFileHandle fileHandleForUpdatingAtPath: newPath];
        if (![fm isReadableFileAtPath:txtPath])
        {
            NSLog(@"file is not readable");
            return 0;
        }
      
        if (![fm isWritableFileAtPath:newPath])
        {
            NSLog(@"file is not writabel");
            return 0;
        }
        
        NSData* tmpData = [fileReading readDataToEndOfFile];
        [fileWriting writeData:tmpData];
        NSLog(@"%@ file lenght: %lu", newPath, [tmpData length]);
        [fileWriting writeData:tmpData];
        [fileWriting seekToFileOffset:10];
        NSString* info = @"2013.3.6 ztercel";
        NSData* data2 = [NSData dataWithBytes: [info UTF8String] length:[info length]];
        [fileWriting writeData:data2];
    
        [fileReading closeFile];
        [fileWriting closeFile];
        
        [fm removeItemAtPath:txtPath error:nil];
        [fm removeItemAtPath:newPath error:nil];
        NSLog(@"handle successfully");
    }
    return 0;
}

